<?php
namespace app\api\controller;

use app\admin\model\information\InventoryClass;
// use app\admin\model\information\Shelves;
use app\common\model\Shelves;
use app\admin\model\inventory\Kc;
use app\admin\model\information\Actionlog;
use app\common\controller\Api;
// use app\common\library\Log;
use think\Log;
use think\Config;
use think\Db;
use think\Exception;
use fast\Tree;
use addons\crontab\controller\Pda;
use app\common\model\Temporary;
use app\admin\model\inventory\Wmskc;
use app\admin\model\inventory\Wmskcview;
use app\common\model\Inventory;
use app\common\model\Warehouse;
use think\db\Query;
use app\common\model\InvShelvesLatest;
use app\admin\model\outhouse\CheckVouchList;
use app\admin\model\outhouse\CheckVouch;
use app\admin\model\inventory\Procure;
//use app\admin\model\inventory\VProcure;
use app\admin\model\inventory\VTemporary;
use app\admin\model\outhouse\Tpdj;
use app\admin\model\outhouse\TpdjList;
use app\admin\model\outhouse\TpdjListView;
use app\admin\model\Mcode;
use app\admin\library\Auth;
use app\admin\model\information\KisBaseinfo;
use app\admin\model\inventory\MaterialListView;
use app\admin\model\inventory\VProcure;
use app\admin\model\Kisapi;
use think\Request;
/**
 * wms前台在线版接口
 */
class WmsOnline extends Api
{

    protected $noNeedLogin = [
        '*'
    ];

    protected $noNeedRight = [
        '*'
    ];

    protected $pc_type_arr = [
        0 => 1, //收货对应pctype的1
        1 => 5,  //上架对应pctype的5（原货架（可能是库区），现货架）源单上架
        3 => 2,  //领料出库对应pctype的2
        4 => 14, //产品入库 ---new
        5 => 15, //销售出库 ---new
        11 => 3,  //其他入库
        12 => 4,  //其他出库
        13 => 9, //盘点
        14 => 6, //采购退回
        15 => 7, //领料退回
        16 => 8, //调拨
        17 => 10, //直接上架
        18 => 11, //直接领料
        2  => 12  //拣货单-》拣货出库
    ];
    protected $pda_typeflag_arr = [
        1 => 'SIN', //收货对应pctype的1
        12  => 'PK',  //拣货单-》拣货出库
        5 => 'IN',  //上架对应pctype的5（原货架（可能是库区），现货架）源单上架
        2 => 'OUT',  //领料出库对应pctype的2
        3 => 'OIN',  //其他入库
        4 => 'OOUT',  //其他出库
        //13 => 9, //盘点
        6 => 'QASN', //采购退回
        7 => 'QOUT', //领料退回
        8 => 'DB', //调拨
        10 => 'IN', //直接上架
        11 => 'OUT', //直接领料
        14 => 'PIN',//产品入库
        15 => 'SEOUT'//销售出库
    ];

    protected $table = '';

    protected $page = 1;

    protected $pagesize = 15;

    protected $keyword = '';

    protected $scan_keyword = '';

    protected $order = [];

    // ['order','id'=>'desc']
    protected $condition = [];

    public function _initialize()
    {
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        $params = request()->param();
        $this->page = ! isset($params['page']) ? 1 : $params['page']; // 获取当前页数
        $this->pagesize = ! isset($params['pagesize']) ? 15 : $params['pagesize']; // 获取每页数量
        
        if (isset($params['table'])) {
            $this->table = $params['table'];
            // 排序
            if (isset($params['order_str']) && $params['order_str']) {
                $this->order = explode(',', $params['order_str']);
            }
            
            $condition = [];
            // 条件
            if (isset($params['condition_str'])) {
                $condition = json_decode(htmlspecialchars_decode($params['condition_str']), true); //
                if (! is_array($condition)) {
                    exception('参数错误!');
                }
                
                if (isset($condition['keyword']) && $condition['keyword']) {
                    $this->keyword = $condition['keyword'];
                }
                
                if (isset($condition['scan_keyword']) && $condition['scan_keyword']) {
                    $this->scan_keyword = $condition['scan_keyword'];
                    $this->keyword = ''; // 有扫描关键字的，忽略
                }
                
                unset($condition['keyword']);
                unset($condition['scan_keyword']);
            }
            
            $this->condition = $condition;
        }
        
        parent::_initialize();
    }

    /**
     * 获取仓库列表
     */
    public function getWarehouseList()
    {
        //$data = \app\common\model\Warehouse::getList();
        $where = [
            'switch' => 1
        ];
        $field = 'id,number,name';
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        
        $data = Warehouse::field($field)->where($where)->
        // ->order($this->order)
        paginate($this->pagesize);
        
        return json($data);
    }

    /**
     * 获取货架列表
     */
    public function getShelvesList()
    {
        $where = [
            'switch' => 1,
            //'deletetime' => null
        ];
        
        $field = 'id,number,name,warehouse_id,type,ifnull(remark,"") remark,
ifnull(row_number,"") row_number,ifnull(column_number,"") column_number,ifnull(layers_number,"") layers_number,
ifnull(max_number,"") max_number,inv_ids,max_box,
ifnull(max_weight,"") max_weight,ifnull(max_volume,"") max_volume,
ifnull(`long`,0) `long`,ifnull(width,0) width,ifnull(high,0) high,cBatch,
ifnull(size,"") size,ifnull(picking_ordre,"") picking_ordre,ifnull(listing_order,"") listing_order,ifempty';
        
        if ($this->keyword) {
            $where['name|number|remark'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
            if(isset($where['ifempty'])&&!$where['ifempty']){
                unset($where['ifempty']);
            }
            if(isset($where['type'])&&!$where['type']){
                unset($where['type']);
            }
        }
        
        // 查询全部
        if (isset($where['row_number']) && ! $where['row_number']) {
            unset($where['row_number']);
        }
        if (isset($where['column_number']) && ! $where['column_number']) {
            unset($where['column_number']);
        }
        
        $data = Shelves::field($field)->where($where)
            ->order($this->order)
            ->paginate($this->pagesize);
        
        return json($data);
    }

    /**
     * 获取货架 行号
     */
    public function getShelvesRows()
    {
        $field = "number row_number,concat('第',row_number,'行') row_str";
        $where = [
            'switch' => 1,
            'row_number' => [
                'NEQ',
                'not null'
            ]
        ];
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        
        $data = Shelves::field($field)->where($where)
            ->group('row_number')
            ->order($this->order)
            ->select();
        
        return json($data);
    }

    /**
     * 获取货架 列号
     */
    public function getShelvesColumns()
    {
        $field = "number column_number,concat('第',column_number,'列') column_str";
        $where = [
            'switch' => 1
        ];
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        
        $data = Shelves::field($field)->where($where)
            ->group('column_number')
            ->order($this->order)
            ->select();
        
        return json($data);
    }

    /**
     * 获取货架分类限制
     *
     * @return void
     */
    public function getShelvesInvclass($type = 1)
    {
        $data = db('shelves_invclass')->alias('a')
            ->field('a.*,(select b.cInvCCode from fa_inventory_class b where b.id=a.inv_class_id) classification_id')
            ->select();
        
        // 保存文件
        save_json_by_type('shelvesInvclass', $data);
        if ($type == 1) {
            $this->success('成功', $data);
        }
    }

    /**
     * 获取采购入库
     *
     * @return void
     */
    public function getProcureList()
    {
        $field = 'a.id,a.auto_id,a.warehousing_code pcode,a.warehousing_date pdate,
a.factory_name,a.factory_code,a.row_id,a.inventory_number inv_number,a.quantity,a.warehousing_quantity,(a.quantity - a.warehousing_quantity) no_quantity,
(round(a.warehousing_quantity*100/a.quantity,2)) rat,a.type,b.mbatch,b.fCoefficient,b.store_unit,b.store_unit_code,
IFNULL(b.default_warehouse_id,0) warehouse_id,IFNULL(b.default_warehouse_name,"") warehouse_name,
b.name inv_name,IFNULL(b.specification,"") inv_specification,b.unit unit_name,
IFNULL(a.shelves_id,0) shelves_id,IFNULL(b.shelves_name,"") shelves_name,
(select name from fa_warehouse where id=a.warehouse_id) to_warehouse_name,
(select name from fa_shelves where id=a.shelves_id) to_shelves_name,IFNULL(a.cBatch,"") cBatch,
IFNULL(a.lastest_warehouse_id,0) lastest_warehouse_id,IFNULL(a.lastest_shelves_id,0) lastest_shelves_id,
IFNULL(a.lastest_warehouse_name,"") lastest_warehouse_name,IFNULL(a.lastest_shelves_name,"") lastest_shelves_name,
b.name,IFNULL(b.specification,"") specification,b.attributes,b.unit_code,b.unit,IFNULL(a.remark,"") remark,
IFNULL(a.F_104,"") F_104';
        
        $where = [
            'a.no_quantity' => [
                'GT',
                0
            ]
        ];
        
        if ($this->keyword) {
            $where['name|number|specification|shelves_name|warehousing_code'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
            if(isset($where['uid'])){
                //显示全部
                $procure_type_ids = db('admin')->where('id',$where['uid'])->value('procure_type_ids','');
                if($procure_type_ids == ''){
                    return ;
                }

                if(isset($where['type'])){
                    if($where['type']){
                        //生产任务、产品入库
                        $procure_type_ids = str_replace('0','',$procure_type_ids);//去掉0
                        $arr = array_filter(explode(',',$procure_type_ids));//去掉空
                        if(!$arr){
                            return ;
                        }
                        $where['type'] = ['IN',$arr];
                    }else{
                        //采购
                        $procure_type_ids = db('admin')->where([
                            'id' => $where['uid'],
                            'procure_type_ids' => ['like','0%']
                        ])->value('procure_type_ids','');
                        if($procure_type_ids==''){
                            return ;
                        }
                    }
                }else{
                    //入库任务列表进来的
                    $where['type'] = ['IN',$procure_type_ids];
                }
                unset($where['uid']);
            }
        }
        
        if (isset($where['commit_quantity']) && $where['commit_quantity'] == '>0') {
            $where['warehousing_quantity'] = [
                'GT',
                0
            ];
            unset($where['commit_quantity']);
        }
        
        $data = Procure::field($field)->alias('a')
            ->join('inventory b', 'a.inventory_number=b.number', 'left')
            ->where($where)
            ->group('a.id')
            ->order([
            'a.warehousing_code' => 'desc',
            'a.row_id' => 'asc'
        ])
            ->paginate($this->pagesize);
        
        return json($data);
    }
    
    /**
     * 获取物料档案表
     */
    public function getInventoryList()
    {
        $field = 'id,ifnull(warehouse_id,0) warehouse_id,ifnull(shelves_id,0) shelves_id,ifnull(shelves_name,"") tj_shelves_name,number,name,ifnull(specification,"") specification,attributes,
        classification_name,classification_id,unit,unit_code,mbatch,ifnull(safe_num,"") safe_num,ifnull(max_num,"") max_num,
        ifnull(min_num,"") min_num,ifshangjia,ifjianhuo,store_unit,store_unit_code,fCoefficient,
        (select concat(v.warehouse_name,"-",v.shelves_name) from fa_inv_shelves_latest_view v where v.inv_id=id) lastest_shelves_name';
        //
        $where = [
            'deletetime' => null
            // 'classification_id' => ['not like','0810%']
        ];
        
        if ($this->keyword) {
            $where['name|number|specification|shelves_name'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        
        $data = Inventory::field($field)->where($where)->
        // ->order($this->order)
        paginate($this->pagesize);
        
        return json($data);
    }

    /**
     * 获取物料库存列表
     *
     * @return void getKcList?page=2&pagesize=10&order=id asc
     *         {"total":2194,"per_page":"10","current_page":2,"last_page":220,"data":[{}]}
     */
    public function getKcList()
    {
        $field = 'id,warehouse_id,warehouse_number,warehouse_name,
inv_id,inv_name name,inv_number cInvCode,IFNULL(inv_specification,"") specification,
inv_unit unit,inv_unit_code,shelves_id,shelves_name,shelves_number,shelves_type,
store_quantity,inv_store_unit store_unit,inv_store_unit_code store_unit_code,fCoefficient,
quantity iQuantity,quantity fqty,cur_quantity,classification_id,classification_name,cBatch,mbatch';
        
        $where = [
            'status' => 1,
            'quantity' => [
                'GT',
                0
            ]
        ];
        
        if ($this->keyword) {
            $where['inv_name|inv_number|inv_specification|shelves_name|cBatch'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        if ($this->scan_keyword) {
            $where['inv_number|shelves_number'] = [
                "like",
                "%{$this->scan_keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
            if(isset($where['inv_id'])&&!$where['inv_id']){
                unset($where['inv_id']);
            }
        }
        //Log::error($where);
        
        $data = Wmskcview::field($field)->where($where)//Wmskc
            ->order($this->order)
            ->paginate($this->pagesize);

        //减去在途
        if($data){
            foreach($data as &$obj){
                if($obj->fqty - $obj->now_kc<=0){
                    $obj->fqty = 0;
                    $obj->iQuantity = 0;
                    $obj->store_quantity = 0;
                    $obj->now_kc = 0;
                }else{
                    $fqty = $obj->fqty;
                    $obj->now_kc = $obj->now_kc;
                    $obj->fqty = $fqty - $obj->now_kc;
                    $obj->iQuantity = $fqty - $obj->now_kc;
                    $obj->store_quantity = $obj->iQuantity/$obj->fCoefficient;
                }
            }
        }
        //
            //Log::error($data);
        return json($data);
    }

    /**
     * 获取物料库存明细
     *
     * @return void
     */
    public function getKcDetail()
    {
//         $field = 'id,warehouse_id,warehouse_number,warehouse_name,
// inv_id,inv_name name,inv_number cInvCode,IFNULL(inv_specification,"") specification,
// inv_unit unit,inv_unit_code,shelves_id,shelves_name,shelves_number,shelves_type,
// quantity iQuantity,cur_quantity,classification_id,classification_name,cBatch';
        $field = "id kc_id,sum(quantity) fqty,inv_unit_code";
        $where = [
            'status' => 1,
            'quantity' => [
                'GT',
                0
            ]
        ];
        $group = [];
        
        if ($this->keyword) {
            $where['inv_name|inv_number|inv_specification|shelves_name'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        if (isset($this->condition['cBatch'])) {
            $group = [
                'cBatch'
            ];
        }

        $data = Wmskcview::field($field)->where($where)//Wmskc
            ->order($this->order)
            ->group($group)
            ->select();
        
        //减去在途
        if($data){
            foreach($data as &$obj){
                if($obj->fqty - $obj->now_kc<0){
                    $obj->fqty = 0;
                }else{
                    $obj->fqty = $obj->fqty - $obj->now_kc;
                }
            }
        }
        
        return json($data);
    }

    /**
     * 获取pda入库单（外购入库）
     *
     * @return void
     */
    public function getIncheckList()
    {
        $field = 'id,source_code,order_code pcode,order_date pdate,
inv_id,inv_name,number inv_number,IFNULL(specification,"") inv_specification,
unit unit_name,shelves_id,shelves_name,quantity,cBatch,warehouse_name,pass_status,remark';
        
        $where = [
            'status' => 1,//已复核
            'order_list' => 1,
            // 'order_list' => ['IN',[1,14]],
            'pass_status' => 0 //未质检的单
        ];
        
        if ($this->keyword) {
            $where['inv_name|number|specification|shelves_name|source_code|cBatch'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
            // if (stripos($where['order_list'], ',')) {
            //     $where['order_list'] = [
            //         'IN',
            //         explode(',', $where['order_list'])
            //     ];
            // }
            // if($where['pass_status']){
            //     //移库动作，只看源单是mes外包入库
            //     $where['source_code'] = [
            //         "like",
            //         "MES%"
            //     ];
            // }
        }
        
        $data = VTemporary::field($field)->where($where)
            ->order($this->order)
            ->paginate($this->pagesize);
        
        return json($data);
    }

    /**
     * 获取mes产品入库，在入库任务那，状态status=2的单据
     *
     */
    public function getPIncheckList()
    {
        $field = 'id,source_code,warehousing_code pcode,order_date pdate,
        fItemId inv_id,inv_name,inventory_number inv_number,IFNULL(specification,"") inv_specification,
unit unit_name,shelves_id,shelves_name,quantity,store_quantity,unit,store_unit,cBatch,
warehouse_name,warehouse_id,remark,status';

        $where = [
            'type' => 1
        ];
        
        if ($this->keyword) {
            $where['inv_name|inventory_number|specification|shelves_name|source_code|warehousing_code|cBatch'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        
        $data = VProcure::field($field)->where($where)
            ->order($this->order)
            ->paginate($this->pagesize);
        
        return json($data);
    }

    //获得待复核的pda单据
    public function getTemportFhList(){
        $field = 'id,source_code,order_code pcode,order_date pdate,createtime,status,
        inv_id,inv_name,number inv_number,IFNULL(specification,"") inv_specification,
        unit,store_unit,shelves_id,shelves_name,quantity,store_quantity,cBatch,warehouse_name,pass_status,
        remark';
        
        $data = [];
        $where = [
            'status' => ['IN',[0]],//,2 待复核的单
            'u8_code' => null,
            // 'pass_status' => 0 //未质检的单
        ];
        
        if ($this->keyword) {
            $where['inv_name|number|specification|shelves_name|source_code|cBatch|order_code'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
            if(isset($where['order_type'])){
                $pda_flag = getPdaFlag($where['uuid']);
                if(!$pda_flag){
                    $this->error('请先在WMS平台绑定PDA设备');
                }

                $pda_user_arr = config('site.pda_user');
                if(!isset($pda_user_arr[$pda_flag])){
                    $this->error('请先在WMS平台绑定PDA用户');
                }else{
                    $where['u8username'] = $pda_user_arr[$pda_flag];
                }

                switch($where['order_type']){
                    case 0://外购入库
                        $where['order_list'] = 1;
                        break;
                    case 4://产品入库
                        $where['order_list'] = 14;
                        break;
                    case 16://调拨
                        $where['order_list'] = 8;
                        break;
                }
                unset($where['uuid']);
                unset($where['order_type']);
            }
            
            if($where['order_list']==8){
                //得到pda单据里，未复核的调拨单号
                $db_pda_code_arr = db('temporary')->where($where)
                ->field('order_code')
                ->group('order_code')
                ->column('order_code');
                
                if($db_pda_code_arr){
                    $data = TpdjListView::where([
                        'status' => 0,
                        'code' => ['IN',$db_pda_code_arr]
                    ])
                    ->field('code pcode,code_date createtime,inv_name,inv_id,
                    inv_number,inv_specification,unit,store_unit,quantity,store_quantity,
                    warehouse_name,warehouse_change_name,shelves_name,shelves_change_name,
                    cBatch,status')
                    ->order('code_date desc')
                    ->paginate($this->pagesize);
                }
            }else{
                $data = VTemporary::field($field)->where($where)
                ->order($this->order)
                ->paginate($this->pagesize);
            }
            return json($data);
        }
    }

    /**
     * 获取领料列表
     *
     * @return void
     */
    public function getMaterialList($type = 3)
    {
        $field = 'id,auto_id,row_id,material_code pcode,order_date pdate,cdepcode,cdepname,
quantity,commit_quantity,warehouse_id,ifnull(tj_shelves_id,0) tj_shelves_id,ifnull(shelves_name,"") tj_shelves_name,
ifnull(cWhcode,"") warehouse_code,ifnull(warehouse_name,"") warehouse_name,cBatch,
inventory_number inv_number,inv_name,ifnull(specification,"")inv_specification ,inv_id,
fUnitId unit_code,unit unit_name,case source when source=1 then "MES" else "KIS" end as source ,
ifnull(cUser_Id,"") cUser_Id,ifnull(cUser_Name,"") cUser_Name,(round(quantity - commit_quantity,4)) no_quantity,
ifnull(remark,"") remark,(round(commit_quantity*100/quantity,2)) rat,
ifnull(kc_tj_cBatch,"") kc_tj_cBatch,store_unit_code,store_unit,fCoefficient,
ifnull(seorder_batch_shelves,"") seorder_batch_shelves,store_quantity
'; 
        //kc_tj_cBatch按日期正序 取批号库区信息，   seorder_batch_shelves 按订单上面的批号取库区信息
        $where = [
            'type' => $type
            // 'no_quantity' => [
            //     'GT',
            //     0
            // ]
        ];
        
        if ($this->keyword) {
            $where['inv_name|inventory_number|specification|shelves_name|material_code|cBatch|fInterId'] = [
                "like",
                "%{$this->keyword}%"
            ];
        }
        
        // 合并查询条件
        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }
        
        $data = MaterialListView::field($field)->alias('a')
            ->where($where)
            //->where("commit_quantity<quantity")//只显示未发完的
            ->group('a.id')
            ->order([
                'order_date' => 'desc',
                'material_code' => 'desc',
                'row_id' => 'asc'
            ])
            ->paginate($this->pagesize);
        
        return json($data);
    }

    public function getUsers($type = 1)
    {
        // 读u8用户
        // $data = Db::connect('database.sec')->table('UA_User_Ex')->field('cUser_Id userid,cUser_Name username')->select();
        
        // 读wms平台管理员
        $data = db('admin')->field('CONCAT("wms","_",id) userid,username,nickname')
            ->where([
            'status' => 'normal',
            'username' => [
                'NEQ',
                'admin'
            ]
        ])
            ->select();
        
        save_json_by_type('user', $data);
        if ($type == 1) {
            $this->success('成功', $data);
        }
    }

    /*
     * 物料分类
     */
    public function getInventoryClassList($type = 1)
    {
        $data = InventoryClass::geTreeData();
        $tree = InventoryClass::listToTreeByRecursion($data);
        save_json_by_type('inventory_class', $tree);
        if ($type == 1) {
            $this->success('成功', $tree);
        }
    }

    /*
     * 货架、库区 树
     */
    public function getShelvesTree($type = 1)
    {
        $shelves = new Shelves();
        $tree = $shelves->getTreeData();
        $tree = InventoryClass::listToTreeByRecursion($tree);
        save_json_by_type('shelves_tree', $tree);
        if ($type == 1) {
            $this->success('成功', $tree);
        }
    }

    /*
     * 生成物料和货架的最新关联信息,数据靠计划任务自动生成
     */
    public function getShelvesLatest($condition = [])
    {
        $data = db('inv_shelves_latest_view')
            ->field('warehouse_name,shelves_name')
            ->where($condition)
            ->select();
        
        return json($data);
    }

    /**
     * 获取盘点任务
     *
     * @return void
     * @throws \think\exception\DbException
     */
    public function getCheckvouchList()
    {
        $uuid = $this->condition['uuid'];
        $warehouse_id = $this->condition['warehouse_id'];
        if(!$uuid||!$warehouse_id){
            return [];
        }
        
        $main = collection(CheckVouch::where([
            'status' => 1,
            'pda' => ['like',"%{$uuid}%"],
            'warehouse_id' => $warehouse_id
        ])->field('id,code,code_date,book_date,warehouse_id,type,inv_number_start,
        inv_number_end,ifnull(shelves_des,"") shelves_des,ifnull(inv_class_name,"") inv_class_name,remark')->select())->toArray();
        $detail = [];
        if ($main) {
            foreach ($main as $m) {
                $rows = collection(CheckVouchList::where([
                    'code' => $m['code']
                    // 'scan_flag'=>0 //未扫描的
                ])->alias('a')
                ->join('inventory b','a.inv_id=b.id','left')
                ->field('a.id,a.inv_id,a.inv_name,a.cInvCode inv_number,a.code,iQuantity kc_qty,iQuantity/b.fCoefficient kc_auxqty,
                ifnull(iCVCQuantity,"") check_qty,ifnull(iCVCQuantity/b.fCoefficient,"") check_auxqty,
                a.shelves_id,isnew,a.shelves_name,scan_flag,
                ifnull(scantime,"") scantime,ifnull(b.specification,"") specification,
                ifnull(cBatch,"") cBatch,b.store_unit,b.store_unit_code,b.fCoefficient,
                b.unit,b.unit_code')
                ->select())
                ->toArray();
                $detail[$m['code']] = $rows;
            }
        }
        
        $data = [
            'main' => $main,
            'detail' => $detail
        ];
        return json_encode($data);
        // 保存文件
        //save_json_by_type('checkVouch', $data);
        // $this->success('成功',$data);
        //echo 'checkVouch ok';
    }

    //质检放行,改变状态,针对外购
    //针对采购订单的-》待质检通过后，再生成金蝶外购入库单
    //针对mes产品入库->更新入库任务状态2->1,同时生成本地库存库存
    //wg cp 外购  产品
    public function addDbIncheckOrder(){
        $params = request()->param();//pda单号
        $pcode_arr = $params['porders'];
        if(!$pcode_arr||!is_array($pcode_arr)){
            $this->error('参数错误');
        }

        try{
            trace($params,'error');
            // 检查是否存在上次请求时间的会话变量 20250313
            if (cache('wg_'.$params['userid'])) {
                // 计算当前时间与上次请求时间的间隔
                $time_elapsed = time() - cache('wg_'.$params['userid']);
                trace($time_elapsed,'error');
                if ($time_elapsed < 2) {
                    // 若间隔小于 2 秒，返回错误信息
                    $this->error('网络繁忙，请稍后再试');
                }
            }
            // 更新上次请求时间
            cache('wg_'.$params['userid'],time());
            
            if($params['flag']=='wg'){
                //取本地单据，得到金蝶单号
                // 对于采购入库，质检前，不入金蝶，先放WMS，待质检通过后，再生成金蝶外购入库单【无移库动作】
                $pdaorders = db('temporary')->where([
                    'order_code' => ['IN',$pcode_arr],
                    'status' => 1,
                    'pass_status' => 0,
                    'order_list' => 1
                ])
                ->group('order_code')
                ->field('order_code,order_list,u8_code')
                ->select();

                if(!$pdaorders){
                    $this->error('找不到对应PDA单据');
                }

                // 再生成金蝶产品入库单
                $temporaryModel = new Temporary();
                Db::startTrans();
                foreach($pdaorders as $pdaorder){
                    if($pdaorder['u8_code']){
                        continue;
                    }
                    
                    //质检成功
                    $temporaryModel->where([
                        'order_code' => $pdaorder['order_code']
                    ])
                    ->update([
                        'pass_status' => 1 
                    ]);
                    
                    //金蝶外购入库
                    $temps = db('temporary_view')->where([
                        'order_code' => $pdaorder['order_code']
                    ])
                    ->select();
                    
                    $pda = new Pda();
                    $pda->dealTempData($temps,1);//更新本地库存和回写金蝶外购入库
                }
            }else if($params['flag']=='cp'){
                // 产品打码入库，质检通过后，同时更新入库任务状态
                db('procure')->where([
                    'warehousing_code' => ['IN',$pcode_arr],
                    'status' => 2 //待质检
                ])->update([
                    'status' => 1
                ]);
            }
            Db::commit();
        }catch(Exception $e){
            Db::rollback();
            Log::error('pda审核失败错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());
            $this->error('审核失败,'.$e->getMessage());
        }

        $this->success('审核成功');
    }

    /*
    ** 移库，放行后的动作
    */ 
    public function addDbYikuOrder(){
        //循环后，调API,回写数据到金蝶
        $params = request()->param();//pda单号
        $pcode_arr = $params['porders'];
        if(!$pcode_arr||!is_array($pcode_arr)){
            $this->error('参数错误');
        }

        //取本地单据，得到金蝶单号
        $pdaorders = db('temporary')->where([
            'order_code' => ['IN',$pcode_arr],
            'status' => 1,
            'pass_status' => 1,//质检已放行
            'order_list' => 14,//['IN',[1,14]],
            'u8_code' => null
        ])
        ->field('order_code,u8_code,warehouse_id,order_list')
        ->group('order_code')
        ->select();
        
        if(!$pdaorders){
            $this->error('找不到对应PDA单据');
        }

        $backu8 = config('site.backu8');
        if($backu8){
            $kis_data = [];
            try{
                Db::startTrans();
                foreach($pdaorders as $pdaorder){
                    //mes产品入库
                    $temps = db('temporary_view')
                    ->where([
                        'order_code' => $pdaorder['order_code']
                    ])
                    ->select();
                    
                    //20241221 新增内外销方式录入
                    foreach($temps as $temp_row){
                        if(!$temp_row['status']&&!$temp_row['sell_in_out']){
                            //mes外包进来的产品才需要设置销售方式
                            exception("请先在PC端设置是否自营出口");
                        }
                    }
                    //

                    $pda = new Pda();
                    $pda->dealTempData($temps,14);
                }
                Db::commit();
            }catch(Exception $e){
                Db::rollback();
                $this->error('移库失败,'.$e->getMessage());
            }
            $this->success('移库成功');
        }
    }

    /*
    ** 复核pda单据
    */ 
    public function toFh(){
        $this->request->filter(['strip_tags']);
        $uuid = $this->request->post('uuid','');
        $params = $this->request->param();
        $pcode_arr = $params['porders'];
        if(!$pcode_arr||!is_array($pcode_arr)){
            $this->error('参数错误');
        }
        $pda_order_type = $this->request->post('order_type','');//pda单据类型
        $order_list = $this->pc_type_arr[$pda_order_type];
        if(!isset($this->pc_type_arr[$pda_order_type])){
            $this->error('PDA单据类型为空');
        }
        
        Db::startTrans();
        try{
            $pda_typeflag = $this->pda_typeflag_arr[$order_list];//单据前缀
            $pda_flag = getPdaFlag($uuid);//设备类型数组
            
            if(!$pda_flag){
                exception('请先设置对应PDA标识');
            }
            
            if(!$this->checkAuth($params['userid'],'/pages/stockbill/listfh?type='.$pda_order_type)){
                exception('无权复核,请联系管理员');
            }

            //取本地单据，得到金蝶单号
            $pdaorders = db('temporary')->where([
                'order_code' => ['IN',$pcode_arr],
                'status' => 0,//待复核
                'order_list' => $order_list,
                'u8_code' => null
            ])
            ->field('order_code,u8_code,warehouse_id,order_list')
            ->group('order_code')
            ->select();
                //Log::error($pcode_arr);
            if(!$pdaorders){
                exception('单据丢失,请核实');
            }

            $pcode_arr_str = implode(',',$pcode_arr);

            foreach($pdaorders as $pdaorder){

                $postcache = cache('toFhPcode_'.$pdaorder['order_code']);//缓存5分钟
                if(!$postcache){
                    cache('toFhPcode_'.$pdaorder['order_code'],$pdaorder['order_code'],['expire'=>5*60]);
                }else{
                    exception('网络繁忙,请5分钟后再试');
                }

                //mes产品入库、外购入库
                $temps = db('temporary_view')->where([
                    'order_code' => $pdaorder['order_code']
                ])
                ->select();
                $pda = new Pda();
                $pda->dealTempData($temps,$order_list);

                //改变单据复核状态
                db('temporary')->where('order_code',$pdaorder['order_code'])->update([
                    'status' => 1,
                    'result'=> 'PDA【'.$pda_flag.'】复核成功'
                ]);
                cache('toFhPcode_'.$pdaorder['order_code'],null);//成功清空缓存
            }
            
            Db::commit();
        }catch (\Exception $e){
            //跟踪日志，顺便打印出错误地方
            Db::rollback();
            Log::error('错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /*
    ** 供应商列表
    */ 
    public function getSupplierList(){
        $where['PageSize'] = $this->pagesize;
        $where['PageIndex'] = $this->page;
        $where['fKeyword'] = $this->keyword;

        $data = Kisapi::getDataByName('supplier',$where,true);
        
        return json($data);
    }
    /*
    ** 客户列表
    */ 
    public function getCustomerList(){
        $where['PageSize'] = $this->pagesize;
        $where['PageIndex'] = $this->page;
        $where['fKeyword'] = $this->keyword;

        $data = Kisapi::getDataByName('customer',$where,false);
        return json($data);
    }
    /*
    ** 部门列表
    */ 
    public function getDepartmentList(){
        $where['PageSize'] = $this->pagesize;
        $where['PageIndex'] = $this->page;
        $where['fKeyword'] = $this->keyword;

        $data = Kisapi::getDataByName('department',$where,false);
        return json($data);
    }

    /*
     *领料申请 
     */
    public function getMaterialRequest(){

        $where['PageSize'] = $this->pagesize;
        $where['PageIndex'] = $this->page;
        $where['fKeyword'] = $this->keyword;

        if ($this->condition) {
            $where = array_merge($this->condition, $where);
        }

        $data = Kisapi::getDataByName('getMaterialRequest',$where,true);
        return json($data);
    }

    /**
     * 每日8点，自动处理，历史质检单据，
     * MES传递过来的包装产品入库单，如果存在没质检的单据每天8点自动启动质检，
     * 好让仓管点数移库
     */
    public function autoInCheck()
    {
        $now_hour = date('H',time());
        if($now_hour>=7&&$now_hour<=8){
            db('procure')->where([
                'type' => 1,
                'status' => 2 //待质检
            ])->update([
                'status' => 1
            ]);
            Log::info(date('Y-m-d H:i:s',time()).'自动执行质检成功');

            
        }else{
            die('未到自动质检时间');
        }
    }

    /*
     * 入口
     */
    public function getPageList()
    {
        if ($this->table) {
            switch ($this->table) {
                case 'kc':
                    return $this->getKcList();
                    break;
                case 'inventory':
                    return $this->getInventoryList();
                    break;
                case 'warehouse':
                    return $this->getWarehouseList();
                    break;
                case 'shelves':
                    return $this->getShelvesList();
                    break;
                case 'shelvesRows':
                    return $this->getShelvesRows();
                case 'shelvesColumns':
                    return $this->getShelvesColumns();
                case 'shelvesLatest':
                    return $this->getShelvesLatest();
                    break;
                case 'procure':
                    return $this->getProcureList();
                case 'selloutorder':
                    return $this->getMaterialList(3);
                    break;
                case 'incheck':
                    return $this->getIncheckList();
                    break;
                case 'pincheck':
                    return $this->getPIncheckList();
                    break;
                case 'userlogin':
                    $account = $this->condition['username'];
                    $password = $this->condition['password'];
                    if (! $account || ! $password) {
                        $this->error(__('Invalid parameters'));
                    }
                    if (Auth::instance()->login($account, $password)) {
                        $admin = session('admin');
                        $rules = Auth::instance()->getRuleList($admin['id']);
                        $pda_rules = [];
                        if($rules){
                            foreach($rules as $k=>$rule){
                                if(stristr($rule,'/pages/')){//存在
                                    $pda_rules[] = $rule;
                                }
                            }
                        }

                        $this->success([
                            [
                                'id' => $admin['id'],
                                'userid' => "wms_" . $admin['id'],
                                'nickname' => $admin['nickname'],
                                'username' => $admin['username'],
                                'rules' => $pda_rules
                            ]
                        ]);
                    } else {
                        $this->error("不存在该用户名或密码");
                    }
                    break;
                case 'pad':
                    $str = $this->condition['code'];
                    if(!$str){
                        $this->error('参数错误');
                    }else{
                        $now = date('Y-m-d',time());
                        $pdaArr = config('site.pda_flag');
                        $checkpda = false;
                        foreach($pdaArr as $pre=>$flag){
                            if(md5($flag.$now.'pad')==$str){
                                $checkpda = true;
                            }
                        }
                        
                        if(!$checkpda){
                            $this->error('请先绑定Pad');
                        }else{
                            if(session('admin')!=''){
                                $this->success(1);
                            }
                            if (Auth::instance()->login('padadmin', 'sily.123')) {
                                $this->success(2);
                            }
                        }
                    }
                    break;
                case 'outask':
                    return $this->getMaterialList(3);
                    break;
                case 'checkVouch':
                    return $this->getCheckvouchList();
                    break;
                case 'fh':
                    return $this->getTemportFhList();
                    break;
                case 'supplier':
                    return $this->getSupplierList();
                    break;
                case 'customer':
                    return $this->getCustomerList();
                    break;
                case 'department':
                    return $this->getDepartmentList();
                    break;
                case 'materialreq':
                    return $this->getMaterialRequest();
                    break;
            }
        } else {
            exception('table参数错误');
        }
    }

    //判断有无权限
    public function checkAuth($uid,$auth_str = ''){
        if(!$uid||!$auth_str){
            return false;
        }
        
        if(!is_numeric($uid)){
            $temp = explode('_',$uid);
            $uid = $temp[1];
        }
        
        if(!is_numeric($uid)){
            return false;
        }

        $rules = Auth::instance()->getRuleList($uid);
        if(!$rules){
            return false;
        }

        $pda_rules = [];
        if($rules){
            foreach($rules as $k=>$rule){
                if(stristr($rule,'/pages/')){//存在
                    $pda_rules[] = $rule;
                }
            }
            if($pda_rules&&in_array($auth_str,$pda_rules)){
               return true;
            }
        }
        return false;
    }
}
